package com.kelvem.saas.workbanch.core.exception;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Date;

@Slf4j
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {

    // 处理所有未处理的异常
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Object> handleException(Exception e) {
        // 这里可以记录日志等操作

        // 返回自定义的错误信息
        ErrorDetails errorDetails = new ErrorDetails(ErrorCodeEnum.SYS_EXCEPTION.getCode(), ErrorCodeEnum.SYS_EXCEPTION.getMessage(), e.toString());
        log.error(ErrorCodeEnum.SYS_EXCEPTION.toString(), e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorDetails);
    }

    // 可以为特定的异常定义处理逻辑
    @ExceptionHandler(value = SaasException.class)
    public ResponseEntity<Object> handleSaasException(SaasException ex) {
        ErrorCodeEnum errorCodeEnum = ex.getErrorCode();
        String code = errorCodeEnum.getCode();
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        String message = errorCodeEnum.getMessage();
        if (code.compareTo("10000") >= 0 && code.compareTo("20000") < 0) {
            status = HttpStatus.BAD_REQUEST;
        } else if (code.compareTo("20000") >= 0 && code.compareTo("30000") < 0) {
            status = HttpStatus.UNAUTHORIZED;
        }
        if (errorCodeEnum.equals(ErrorCodeEnum.SYS_EXCEPTION)) {
            message = ex.getMessage();
            message = handleMessage(message);
        }
        // 返回自定义的错误信息
        ErrorDetails errorDetails = new ErrorDetails(code, message, ex.toString());
        log.error(errorCodeEnum.toString(), ex);
        return ResponseEntity.status(status).body(errorDetails);
    }

    private String handleMessage(String message) {
        if (message == null) {
            return "null";
        } else if (message.indexOf("SQLIntegrityConstraintViolationException") >= 0) {
            return "唯一编码重复";
        } else {
            return message;
        }
    }

    // 自定义的返回错误信息类
    @Data
    public static class ErrorDetails {
        private String code;
        private String message;
        private String description;
        private Date timestamp = new Date();

        public ErrorDetails(String code, String message, String description) {
            this.code = code;
            this.message = message;
            this.description = description;
        }

        @Override
        public String toString() {
            return String.format("{\"code\":\"%s\",\"message\":\"%s\",\"description\":\"%s\",\"timestamp\":\"%s\"}", code, message, description, timestamp);
        }
    }
}
